import { Component } from 'react';
import { Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { LOGIN_SAGA } from '../../store/action/const';
import { login } from '../../store/action/userAction';

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = { name: '' };
  }
  render() {
    const { isLogin, location, dispatch, login, err, loading } = this.props;
    // 登录
    if (isLogin) {
      const { from = '/user' } = location.state || {};
      return <Redirect to={from} />;
    }
    // 没有登录
    const { name } = this.state;
    return (
      <div>
        <h3>LoginPage</h3>
        <input
          value={name}
          onChange={(e) => {
            this.setState({ name: e.target.value });
          }}
        />
        <p className="red">{err.msg}</p>
        <button onClick={() => login({ name })}>{loading ? 'loading...' : 'click'}</button>
      </div>
    );
  }
}

const mapStateToProps = ({ user }) => ({ isLogin: user.isLogin, err: user.err, loading: user.loading });
const mapDispatchToProps = { login: (userInfo) => ({ type: LOGIN_SAGA, payload: userInfo }) };

export default connect(mapStateToProps, mapDispatchToProps)(Login);
